package com.game.role;

import com.dats.util.Md5Util;
import com.dats.util.TimeUtil;
import com.game.bean.AccountRole;
import com.game.bean.Role;
import com.game.hot.Manager;
import com.game.pool.DataPool;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * author sig
 * since 2017/2/25
 */
public class RoleMg implements RoleI {

    @Override
    public void createRole() {
        Role role = new Role();
        role.setId(Manager.getIdMg().newId(role));
        role.setName(Arrays.asList("jjww", "xxbb").get(ThreadLocalRandom.current().nextInt(2)));
        role.setNickName(Arrays.asList("jjww2", "xxbb2").get(ThreadLocalRandom.current().nextInt(2)));
        role.setCreateTime(TimeUtil.format("yyyy/mm/dd HH:mm:ss", System.currentTimeMillis()));
        role.setOnlineTime(TimeUtil.format("yyyy/mm/dd HH:mm:ss", System.currentTimeMillis()));
        role.setOfflineTime(TimeUtil.format("yyyy/mm/dd HH:mm:ss", System.currentTimeMillis()));
        role.setPlatform(Arrays.asList("windows", "android", "ios").get(ThreadLocalRandom.current().nextInt(3)));
        role.setDeviceId(Md5Util.md5(role.getPlatform()));

        AccountRole accountRole = role.getAccountRole();

        if (null == accountRole) {
            accountRole = new AccountRole();
            accountRole.setId(Manager.getIdMg().newId(accountRole));
            accountRole.setAccount(role.getPlatform() + "#" + role.getDeviceId());
            accountRole.setChannel(role.getPlatform());
            accountRole.setRoleId(role.getId());
            role.setAccountRole(accountRole);
        }
        DataPool.onlineRoleMap.put(role.getId(), role);
    }

    @Override
    public void saveRole() {
        for (Role role : DataPool.onlineRoleMap.values()) {

            if (null == role) continue;
            Manager.getDataMg().saveBean(role);
            Manager.getDataMg().saveBean(role.getAccountRole());
        }
    }

    @Override
    public void loadRole() {
        List<Role> list = Manager.getDataMg().loadBeanList(Role.class,
                "SELECT * FROM `role` limit 0, 100");

        for (Role role : list) {

            if (null == role) continue;
            DataPool.onlineRoleMap.put(role.getId(), role);
            AccountRole accountRole = Manager.getDataMg()
                    .loadBeanByValue(AccountRole.class, role.getId());
            role.setAccountRole(accountRole);
        }
    }

    @Override
    public Role getOnlineRole(long roleId) {
        return DataPool.onlineRoleMap.get(roleId);
    }
}
